﻿package level4.grid_case.astar
{
	import flash.events.*;
	import flash.display.*;
	import level4.grid_case.grid.Grid;
	
	public class PathTool {
		
		// Constants:
		// Public Properties:
		// Private Properties:
		private var scene:Sprite;
		private var player:DisplayObject;
		private var _grid:Grid;
		private var _path:Array;
		private var _index:int;
		private var _cellSize:int = 20;
		// Initialization:
		public function PathTool(scene:Sprite,player:DisplayObject) {
			this.scene = scene;
			this.player = player;
			init();
		}
		private function init():void{
			var cols:int = Math.ceil(scene.width/player.width);
			var rows:int = Math.ceil(scene.height/player.height);
			_grid = new Grid(rows,cols);
			trace(scene.width,player.width,cols,rows)
			/*
			for(var i:int=0;i<100;i++){
				_grid.setWalkable(Math.floor(Math.random() * 30),Math.floor(Math.random() * 30),false);
			}
			*/
			scene.addEventListener(MouseEvent.CLICK,click);
		}

		// Public Methods:
		private function click(e:MouseEvent):void{
			var xpos:int = Math.floor(scene.mouseX/player.width);
			var ypos:int = Math.floor(scene.mouseY/player.height);
			_grid.setEndNode(xpos,ypos);
			xpos = Math.floor(player.x/player.width);
			ypos = Math.floor(player.y/player.height);
			_grid.setStartNode(xpos,ypos);
			findPath();
		}
		private function findPath():void{
			var ast:AStar = new AStar();
			if(ast.findPath(_grid)){
				_path = ast.path;
				_index = 0;
				scene.addEventListener(Event.ENTER_FRAME,enterFrame);
			}
		}
		// Protected Methods:
		private function enterFrame(e:Event):void{
			var tx:Number = _path[_index].x * player.width + player.width/2;
			var ty:Number = _path[_index].y * player.height + player.height/2;
			var dx:Number = tx - player.x;
			var dy:Number = ty - player.y;
			var dist:Number = Math.sqrt(dx*dx+dy*dy);
			if(dist < 1){
				_index ++;
				if(_index >= _path.length){
					scene.removeEventListener(Event.ENTER_FRAME,enterFrame);
				}
			}else{
				player.x += dx * .4;
				player.y += dy * .4;
			}
		}
	}
	
}